package com.ptu.spzx.manager.controller;


import com.ptu.spzx.common.exception.ptuException;
import com.ptu.spzx.manager.service.SysMenuService;
import com.ptu.spzx.manager.service.SysUserService;
import com.ptu.spzx.manager.service.ValidateCodeService;
import com.ptu.spzx.model.entity.system.SysUser;
import com.ptu.spzx.model.entity.user.UserInfo;
import com.ptu.spzx.model.vo.h5.UserInfoVo;
import com.ptu.spzx.model.vo.system.SysMenuVo;
import com.ptu.spzx.model.vo.system.ValidateCodeVo;
import com.ptu.utils.AuthContextUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.ptu.spzx.model.dto.system.LoginDto;
import com.ptu.spzx.model.vo.common.Result;
import com.ptu.spzx.model.vo.common.ResultCodeEnum;
import com.ptu.spzx.model.vo.system.LoginVo;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "用户接口")
@RestController
@RequestMapping(value = "/ac/system/index")
public class IndexController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ValidateCodeService validateCodeService;

    @Autowired
    private SysMenuService sysMenuService;


    //根据用户ID查询用户可以操作的菜单
    @GetMapping("/menus")
    public Result menus() {
        List<SysMenuVo> list = sysMenuService.findMenusByUserId();
        return Result.build(list, ResultCodeEnum.SUCCESS);
    }

    //生成图片验证码
    @GetMapping(value = "/generateValidateCode")
    public Result<ValidateCodeVo> generateValidateCode() {
        ValidateCodeVo validateCodeVo = validateCodeService.generateValidateCode();
        return Result.build(validateCodeVo, ResultCodeEnum.SUCCESS);
    }


    @Operation(summary = "登录接口")
    @PostMapping(value = "/login")
    public Result<LoginVo> login(@RequestBody LoginDto loginDto) {
        if(!StringUtils.hasText(loginDto.getUserName())){
            throw new ptuException(ResultCodeEnum.PARAM_NULL);
        }
        LoginVo loginVo = sysUserService.login(loginDto);
        return Result.build(loginVo, ResultCodeEnum.SUCCESS);
    }

    //获取个人用户信息
    @GetMapping("/userInfo")
    public Result userInfo(){
        return sysUserService.userInfo();
    }

    //用户退出
    @PostMapping(value = "/logout")
    public Result logout() {
        sysUserService.logout();
        return Result.build(null, ResultCodeEnum.SUCCESS);
    }
}
